<?php

namespace app\common\controller\partneradmin;

use app\partneradmin\model\CustomerServiceAccountMiddle;
use app\partneradmin\model\CustomerServicePersonnel;
use app\partneradmin\library\Auth;
use app\partneradmin\model\CustomerServiceAccount;
use think\Cache;
use think\Controller;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

class Base extends Controller
{

    /**
     * 用户对象
     */
    protected $auth;

    /**
     * 登录后台
     */
    protected $admin;

    /**
     * 无需登录的方法,同时也就不需要鉴权了 此处放不需要鉴权的接口
     * @var array
     */
    protected $noNeedLogin = [

    ];

    /**
     * 排除前台提交过来的字段
     * @var array
     */
    protected $excludeFields = [];

    /**
     * 是否开启验证
     * @var array
     */
    protected $modelValidate = true;


    public function _initialize()
    {
        //跨域请求检测
        check_cors_request();
        //ip验证
        check_ip_allowed();
        //用户对象
        $this->auth = new Auth;

        //需要登陆的接口
        if (!$this->auth->match($this->noNeedLogin)) {

            $token = $this->request->header("token");
            $checktoken = $this->auth->checkToken($token);
            if (!$checktoken) {
                $this->error('token错误，请重新登录！', '', [], 9999);
            }

            $this->admin = $this->auth->getUserInfo($token);
            $module = request()->module();
            $controller = request()->controller();
            $action = request()->action();
            if ($module == 'partneradmin' && $controller != 'Index' && $action != 'googleValidator' && $this->admin['is_bind_google'] == 0) {
                Cache::store('redis')->rm($token);
                $this->error('请先绑定谷歌账号', $url = null, $data = null, $code = 1111);
            }
        }
    }


    /**
     * 排除前台提交过来的字段
     * @param $params
     * @return array
     */
    protected function preExcludeFields($params)
    {
        if (is_array($this->excludeFields)) {
            foreach ($this->excludeFields as $field) {
                if (key_exists($field, $params)) {
                    unset($params[$field]);
                }
            }
        } else {
            if (key_exists($this->excludeFields, $params)) {
                unset($params[$this->excludeFields]);
            }
        }
        return $params;
    }

    /**
     * 获取当前登陆用户是否是客服组长、客服人员
     */
    public function getCustomerServiceInfo($customer_service_personnel_name = '', $customer_service_account_name = '')
    {
        //根据权限获取对应的客服账号数据 角色:1=组长,2=组员,3=平台管理员
        $data = [];
        $resData = [
            'total' => 0,
            'list' => [],
            'totalPage' => 0
        ];

        switch ($this->admin['rule']) {
            //组长获取组下所有客服人员跟客服账号数据
            case 1:
//                //获取组长人员信息
//                $infoWhere = [
//                    'partner_admin_id' => $this->admin['id'],
//                    'partner_id' => $this->admin['partner_id']
//                ];
//                if (!empty($customer_service_personnel_name)) {
//                    $infoWhere['name'] = $customer_service_personnel_name;
//                }
//                $info = CustomerServicePersonnel::where($infoWhere)->find();
//
//                if (empty($info)) {
//                    if (!empty($customer_service_personnel_name)) {
//                        $this->success('列表', '', $resData);
//                    }
//                    $this->error('账号数据错误，请重新登录！', '', []);
//                }
//                $data['customer_service_personnel_info'] = $info;
//                $accountWhere = [
//                    'customer_service_group_id' => $info['customer_service_group_id'],
//                    'switch' => 1
//                ];
//                if ($customer_service_account_name != '') {
//                    $accountWhere['username'] = $customer_service_account_name;
//                }
//                //获取客服组下所有默认的客服账号id
//                $customerServiceAccount = CustomerServiceAccount::where($accountWhere)->select()->toArray();
//                $accountIds = array_column($customerServiceAccount, 'id');
//                $customerServiceAccountMiddleList = CustomerServiceAccountMiddle::where(
//                    [
//                        'customer_service_account_id' => ['in', $accountIds]
//                    ]
//                )->select()->toArray();
//                $middleIds = array_column($customerServiceAccountMiddleList, 'id');
//                $data['middle_ids'] = $middleIds;
//                break;
            case 2:
                //获取组员人员信息
                $infoWhere = [
                    'partner_admin_id' => $this->admin['id'],
                    'partner_id' => $this->admin['partner_id']
                ];
                $info = CustomerServicePersonnel::where($infoWhere)->find();
                if (empty($info)) {
                    $this->error('账号数据错误，请重新登录！', '', [], 9999);
                }
                $data['customer_service_personnel_info'] = $info;
                //获取默认账号信息
                $accountWhere = [
                    'customer_service_personnel_id' => $info['id'],
                    'switch' => 1
                ];
                if ($customer_service_account_name != '') {
                    $accountWhere['username'] = $customer_service_account_name;
                }
                $customerServiceAccount = CustomerServiceAccount::where($accountWhere)->select()->toArray();
                $accountIds = array_column($customerServiceAccount, 'id');
                $customerServiceAccountMiddleList = CustomerServiceAccountMiddle::where(
                    [
                        'customer_service_account_id' => ['in', $accountIds]
                    ]
                )->select()->toArray();
                $middleIds = array_column($customerServiceAccountMiddleList, 'id');
                $data['middle_ids'] = $middleIds;
                break;
            case 3:
                $where = [
                    'partner_id' => $this->admin['partner_id'],
                    'switch' => 1
                ];
                //人员筛选
                if (!empty($customer_service_personnel_name)) {
                    $infoWhere = [
                        'partner_id' => $this->admin['partner_id'],
                        'name' => $customer_service_personnel_name
                    ];
                    $info = CustomerServicePersonnel::where($infoWhere)->find();
                    if (empty($info)) {
                        $this->success('列表', '', $resData);
                    }
                    $where['customer_service_personnel_id'] = $info['id'];
                }
                if ($customer_service_account_name != '') {
                    $where['username'] = $customer_service_account_name;
                }
                //获取客服组下所有默认的客服账号id
                $customerServiceAccount = CustomerServiceAccount::where($where)->select()->toArray();
                $accountIds = array_column($customerServiceAccount, 'id');
                $customerServiceAccountMiddleList = CustomerServiceAccountMiddle::where(
                    [
                        'customer_service_account_id' => ['in', $accountIds]
                    ]
                )->select()->toArray();
                $middleIds = array_column($customerServiceAccountMiddleList, 'id');
                $data['middle_ids'] = $middleIds;
                break;
        }
        return $data;
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        if ($this->request->isPost()) {
            $page = $this->request->post('page', 1);
            $size = $this->request->post('page_size', 10);
            $sort = $this->request->post('sort', 'id');
            $order = $this->request->post('order', 'desc');
            $adminId = $this->admin['id'];

            if ($adminId != '') {
                $where['admin_id'] = $adminId;
            }
            $where['is_del'] = 0;
            $list = $this->model
                ->field('*')
                ->where($where)
                ->page($page, $size)
                ->order($sort, $order)
                ->select();
            $total = $this->model->where($where)->count('id');
            $totalPage = ceil($total / $size);
            $data = [
                'total' => $total,
                'list' => $list,
                'totalPage' => $totalPage
            ];
            $this->success('列表', '', $data);
        }
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = $name . '.add';
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $params['admin_id'] = $this->admin['id'];
                    $adminCustomerServiceInfo = $this->getCustomerServiceInfo();
                    switch ($this->admin['rule']) {
                        case 1:
                            $params['customer_service_group_id'] = $adminCustomerServiceInfo['customer_service_personnel_info']['customer_service_group_id'];
                            break;
                        case 2:
                            $params['customer_service_personnel_id'] = $adminCustomerServiceInfo['customer_service_personnel_info']['id'];
                            break;
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success('添加成功');
                } else {
                    $this->error('添加失败');
                }
            }
            $this->error('参数不能为空！');
        }
    }


    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error('不存在的数据', '', [], 404);
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = $name . '.edit';
                        $row->validateFailException(true)->validate($validate);
                    }
                    $params['admin_id'] = $this->admin['id'];
                    $result = $row->allowField(true)->isUpdate(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success('修改成功');
                } else {
                    $this->error('修改失败');
                }
            }
            $this->error('参数不能为空！');
        }
    }

    /**
     * 详情
     */
    public function details($ids = "")
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error('未查询到数据！', '', [], 404);
        }
        $this->success('详情数据', '', $row);

    }

    /**
     * 删除（软删）
     */
    public function del($ids = "")
    {
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $v->is_del = 1;
                    $count += $v->save();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success('删除成功');
            } else {
                $this->error('没有需要删除的数据');
            }
        }
        $this->error('参数不能为空！');
    }

    /**
     * 还原
     */
    public function restore($ids = "")
    {

    }

    /**
     * 批量更新
     */
    public function multi($ids = "")
    {

    }

    /**
     * 数据的设置操作, 目前有  开关  是否默认  状态
     */
    public function setup($ids = "")
    {
        $type = $this->request->post("type");
        $val = $this->request->post("val");
        $field = $type;
        switch ($type) {
            case 'switch':
            case 'status':
                $data[$field] = $val;
                $where['id'] = ['in', $ids];
                break;
            case 'is_default':
                if ($val == 1) {
                    $oldwhere['id'] = ['neq', $ids];
                    $oldwhere['is_default'] = 1;
                    $this->model->update(['is_default' => 0], $oldwhere);
                    $data[$field] = $val;
                    $where['id'] = $ids;
                }
                break;
            default:
                $this->error('不存在的业务');
                break;
        }
        $this->model->update($data, $where);
        $this->success('操作成功');
    }
}